package cn.hyh.core.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Servlet;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther :hyh
 * @desc :  德鲁伊链接池的相关配置。
 * @date :2019/4/21
 */
@Configuration
public class DruidConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource  dataSource() {
        return new DruidDataSource();
    }

    /**
     *  配置druid监控
     *  1.注册一个后台管理的servlet
     *  2.注册一个监控的filter
     */

    @Bean
    public ServletRegistrationBean statViewServlet() {
        //配置该servlet的访问路径
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String, String> map = new HashMap<>();
        map.put("loginUsername", "admin");
        map.put("loginPassword", "123456");
        map.put("allow", "");//表示允许所有的进行访问
//        map.put("deny", "192.168.1.1");//表示禁止谁访问
        //通过设置初始化参数来配置  后台管理的密码等。
        bean.setInitParameters(map);
        return bean;
    }

    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean filter = new FilterRegistrationBean();
        filter.setFilter(new WebStatFilter());
        filter.addUrlPatterns("/*");
        Map<String, String> initParam = new HashMap<>();
        initParam.put("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        //通过初始化参数来配置拦截和放行的请求
        filter.setInitParameters(initParam);
        return filter;
    }

}
